package org.jeecg.modules.submodules.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import io.netty.util.internal.StringUtil;
import org.apache.catalina.User;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.submodules.entity.Car;
import org.jeecg.modules.submodules.entity.UserCar;
import org.jeecg.modules.submodules.entity.vo.UserCarVo;
import org.jeecg.modules.submodules.service.ICarService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;

import org.jeecg.modules.submodules.service.IUserCarService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 车辆信息表
 * @Author: jeecg-boot
 * @Date: 2020-07-04
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "车辆信息表")
@RestController
@RequestMapping("/car")
public class CarController extends JeecgController<Car, ICarService> {
    @Autowired
    private ICarService carService;
    @Autowired
    private IUserCarService userCarService;
    @Autowired
    private ISysUserService userService;
    /**
     * 分页列表查询
     *
     * @param car
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "车辆信息表-分页列表查询")
    @ApiOperation(value = "车辆信息表-分页列表查询", notes = "车辆信息表-分页列表查询" +
            "\n 支持模糊查询的字段 车牌号(carNumber),默认驾驶员(defaultDriver),非默认曾驾驶员(beforeDriver)")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(UserCarVo carVo,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        Page page = new Page<UserCarVo>(pageNo, pageSize);
        List<UserCarVo> list = carService.getListOfUserCarVo(carVo);
        if (list.size()<pageSize){
            page.setRecords(list);
        }else {
            page.setRecords(PageUtil.pageBySubList(list,pageSize,pageNo));
        }
        page.setTotal(list.size());
        IPage<UserCarVo> pageList = page;
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param
     * @return
     */
    @AutoLog(value = "车辆信息表-添加")
    @ApiOperation(value = "车辆信息表-添加", notes = "车辆信息表-添加\n" +
            "Car类：\n" +
            "car:{\n" +
            "ID  不填\n" +
            "CAR_NUMBER  车牌号 必填\n" +
            "CAR_FRAME_NUMBER 车架号 选填\n" +
            "ANNUAL_CHECK_TIME 年检时间 选填 以结束时间为准\n" +
            "TRAFFIC_INSURANCE_TIME 交强险时间 选填 以结束时间为准\n" +
            "BUSINESS_INSURANCE_TIME 商业险时间 选填 以结束时间为准\n" +
            "CAR_HITCH_NUMBER 车挂号 选填\n" +
            "CAR_STATUS 车辆状态 0：空闲 1: 使用中\n" +
            "USER_ID  默认绑定司机ID 必填\n" +
            "}")
    @PostMapping(value = "/addOrEdit")
    public Result<?> addOrEdit(@RequestBody JSONObject object) {
        Car car = object.toJavaObject(Car.class);
        car.setId(object.getString("carId"));
            if (StringUtil.isNullOrEmpty(car.getId())) {

            if (!StringUtil.isNullOrEmpty(car.getCarNumber())) {
                car.setId(UUIDGenerator.generate());
                boolean flag = carService.save(car);
                if (flag) {
                    userCarService.save(new UserCar()
                                        .setId(UUIDGenerator.generate())
                                        .setCarId(car.getId())
                                        .setUserId(car.getUserId())
                                        .setCreatedTime(new Date())
                                        .setIsDefault(1)
                    );
                    return Result.ok("保存成功");
                }
            } else {
                return Result.error("车牌号不能为空！");
            }
        } else {
            boolean flag = carService.updateById(car);
            if (flag) {
                userCarService.update(new UserCar().setUserId(car.getUserId()),new QueryWrapper<UserCar>()
                        .eq("CAR_ID",car.getId())
                        .eq("IS_DEFAULT",1)
                );
                return Result.ok("保存成功");
            } else {
                return Result.error("保存失败！");
            }
        }
        return Result.error("保存失败！");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "车辆信息表-通过id删除")
    @ApiOperation(value = "车辆信息表-通过id删除", notes = "车辆信息表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        boolean flag = carService.removeById(id);
        if (flag) {
            userCarService.remove(new QueryWrapper<UserCar>().eq("CAR_ID",id));
            return Result.ok("删除成功!");
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "车辆信息表-批量删除")
    @ApiOperation(value = "车辆信息表-批量删除", notes = "车辆信息表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        boolean flag = this.carService.removeByIds(Arrays.asList(ids.split(",")));
        if (flag) {
            userCarService.remove(new QueryWrapper<UserCar>().in("CAR_ID",ids));
            return Result.ok("删除成功!");
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "车辆信息表-通过id查询")
    @ApiOperation(value = "车辆信息表-通过id查询", notes = "车辆信息表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        UserCarVo car = carService.getUserCarVoDetail(id);
        if (car != null) {
            return Result.ok(car);
        }else {
            return Result.error("没有查询到对应车辆信息");
        }

    }

    /**
     * 导出excel
     *
     * @param request
     * @param car
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Car car) {
        return super.exportXls(request, car, Car.class, "车辆信息表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Car.class);
    }

}
